import React, { useState, useEffect } from 'react';
import { 
  Box, 
  Typography, 
  Chip, 
  Button, 
  Paper, 
  CircularProgress,
  Grid,
  Container,
  Alert
} from '@mui/material';
import { motion } from 'framer-motion';
import axios from 'axios';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../AuthContext';
import { API_PATHS, getAuthHeaders } from '../../../config/apiConfig';

interface Tag {
  id: number;
  name: string;
}

const UserTagSelection: React.FC = () => {
  const [tags, setTags] = useState<Tag[]>([]);
  const [selectedTags, setSelectedTags] = useState<number[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [saving, setSaving] = useState(false);
  const navigate = useNavigate();
  const { user } = useAuth();

  useEffect(() => {
    // 如果用户未登录，重定向到登录页面
    if (!user) {
      navigate('/login');
      return;
    }

    // 获取所有可用标签
    const fetchTags = async () => {
      try {
        setLoading(true);
        // 使用正确的API路径获取所有标签
        // 根据后端API，直接使用 /api/tag/tags 路径获取标签
        const response = await axios.get('/api/tag/tags', {
          headers: getAuthHeaders(),
          params: { page: 1, size: 50 }
        });
        setTags(response.data);
      } catch (err) {
        console.error('获取标签失败:', err);
        setError('获取标签失败，请稍后重试');
      } finally {
        setLoading(false);
      }
    };

    fetchTags();
  }, [user, navigate]);

  const handleTagClick = (tagId: number) => {
    setSelectedTags(prev => {
      if (prev.includes(tagId)) {
        return prev.filter(id => id !== tagId);
      } else {
        return [...prev, tagId];
      }
    });
  };

  const handleSubmit = async () => {
    if (selectedTags.length === 0) {
      setError('请至少选择一个标签');
      return;
    }

    try {
      setSaving(true);
      // 根据后端接口 POST /api/tag/user-tags 保存用户标签
      // 接口接收 List<Long> tagIds 作为请求体
      await axios.post(
        '/api/tag/user-tags',
        selectedTags,
        { headers: getAuthHeaders() }
      );
      
      // 保存成功后跳转到首页
      navigate('/');
    } catch (err) {
      console.error('保存标签失败:', err);
      setError('保存标签失败，请稍后重试');
    } finally {
      setSaving(false);
    }
  };

  if (loading) {
    return (
      <Container maxWidth="sm" sx={{ mt: 8, display: 'flex', justifyContent: 'center' }}>
        <CircularProgress />
      </Container>
    );
  }

  return (
    <Container component="main" maxWidth="sm">
      <Box
        component={motion.div}
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ duration: 0.5 }}
        sx={{
          marginTop: 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
        }}
      >
        <Paper
          elevation={3}
          sx={{
            padding: 4,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',
            width: '100%',
          }}
        >
          <Typography component="h1" variant="h5" gutterBottom>
            选择您感兴趣的标签
          </Typography>
          <Typography variant="body1" color="text.secondary" sx={{ mb: 3, textAlign: 'center' }}>
            这些标签将帮助我们为您推荐更符合您兴趣的内容
          </Typography>
          
          {error && (
            <Alert severity="error" sx={{ width: '100%', mb: 2 }}>
              {error}
            </Alert>
          )}
          
          <Grid container spacing={1} sx={{ mb: 4 }}>
            {tags.map((tag) => (
              <Grid item key={tag.id}>
                <Chip
                  label={tag.name}
                  onClick={() => handleTagClick(tag.id)}
                  color={selectedTags.includes(tag.id) ? "primary" : "default"}
                  sx={{ m: 0.5 }}
                />
              </Grid>
            ))}
          </Grid>
          
          <Box sx={{ display: 'flex', justifyContent: 'space-between', width: '100%' }}>
            <Button
              variant="outlined"
              onClick={() => navigate('/')}
              disabled={saving}
            >
              跳过
            </Button>
            <Button
              variant="contained"
              onClick={handleSubmit}
              disabled={saving || selectedTags.length === 0}
            >
              {saving ? <CircularProgress size={24} /> : '确认'}
            </Button>
          </Box>
        </Paper>
      </Box>
    </Container>
  );
};

export default UserTagSelection;